//implement GThreadTester

#include "GThreadTester.h"
#include "GParallel/GThread.h"

class TestThread : public GThread
{
public:
	TestThread();
	virtual ~TestThread();

	void run();

	void stop();

	void lock();
	void unlock();

private:
	GMutex m_mutex;
	bool m_isRunning;
};

TestThread::TestThread() : m_isRunning(false)
{
}

TestThread::~TestThread()
{
}

void TestThread::run()
{
	m_isRunning = true;
	int i = 0;
	while (m_isRunning)
	{
		i++;
		lock();
		cout << "new thread i = " << i << endl;
		unlock();
		GThread::sleep(100);
	}
}

void TestThread::stop()
{
	m_isRunning = false;
	join();
}

void TestThread::lock()
{
	m_mutex.lock();
}

void TestThread::unlock()
{
	m_mutex.unlock();
}

GThreadTester GThreadTester::_threadTester;

GThreadTester::GThreadTester(const string& testName) : GParallelTester(testName)
{
}

GThreadTester::~GThreadTester()
{
}

GThreadTester& GThreadTester::instance()
{
	return _threadTester;
}

void GThreadTester::testThread()
{
	TestThread thr;
	thr.start();
	for (int i = 0; i < 100; ++i)
	{
		if (i == 50)
			thr.stop();
		thr.lock();
		cout << "main thread i = " << i * 10 << endl;
		thr.unlock();
		GThread::sleep(200);
	}
}

void GThreadTester::testThreading()
{
    GThreading<GThreadTester> tester(this, &GThreadTester::threading);
    tester.start();
    for (int i = 0; i < 100; ++i)
	{
		if (i == 50)
        {
            m_isRunning = false;
            tester.join();
        }

		m_mutex.lock();
		cout << "main threading i = " << i * 10 << endl;
		m_mutex.unlock();
		GThread::sleep(200);
	}
}

void GThreadTester::threading()
{
    m_isRunning = true;
	int i = 0;
	while (m_isRunning)
	{
		i++;
		m_mutex.lock();
		cout << "new threading i = " << i << endl;
		m_mutex.unlock();
		GThread::sleep(100);
	}
}

void GThreadTester::run()
{
	testThread();
	testThreading();
}
